/**
 * @title access_token 全局维护
 * @author 孙
 * Created by ayu on 2017/6/24.
 */
const request = require ('request');
const logger = require ('../utils/logger/Logger');
const wechatAppConfig = require ('../../resources/WechatAppConfig');
const accessTokenDao = require ('../daos/AccessTokenDao');
const jsapiTicketController = require ('./JsapiTicketController');
Date.prototype.format = function ( format )
{
    let o = {
        "M+": this.getMonth () + 1, //month
        "d+": this.getDate (), //day
        "H+": this.getHours (), //hour
        "m+": this.getMinutes (), //minute
        "s+": this.getSeconds (), //second
        "q+": Math.floor ((this.getMonth () + 3) / 3), //quarter
        "S" : this.getMilliseconds () //millisecond
    };
    if (/(y+)/.test (format))
    {
        format = format.replace (RegExp.$1,
            (this.getFullYear () + "").substr (4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp ("(" + k + ")").test (format))
        {
            format = format.replace (RegExp.$1,
                RegExp.$1.length == 1 ? o[ k ] :
                    ("00" + o[ k ]).substr (("" + o[ k ]).length));
        }
    return format;
};
let accessToken = '';
let getAccessToken = () => accessToken;

/**
 * @title 从微信获取新的 access_token
 */
let queryAccessTokenFromWechat = () =>
{
    request ({
        url   : wechatAppConfig.baseAccessTokenUrl,
        method: 'GET'
    }, function ( err, resonpse, _body )
    {
        if (err)
        {
            logger.warn ('向微信服务器请求 access_token 失败', err);
            return;
        }
        let body = JSON.parse (_body);
        accessToken = body.access_token;
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        console.log (`[${time}][AccessToken更新] ${accessToken}\n`);
        saveAccessToken (body);
        jsapiTicketController.queryJsapiTicketFromWechat (accessToken);
        setTimeout (function ()
        {
            queryAccessTokenFromWechat ();
            jsapiTicketController.queryJsapiTicketFromWechat (accessToken);
        }, (body.expires_in - 300) * 1000);
    });
};
/**
 * @title 将 access_token 存入数据库
 * @param data
 */

let saveAccessToken = data =>
{
    accessTokenDao.saveAccessToken ([ data.access_token, data.expires_in * 1000 + Date.now () ], ( done ) =>
    {
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        if (done.isSuccess)
        {
            console.log (`[${time}][access_token] 数据库更新成功`);
        }
        else
        {
            console.log (`[${time}][access_token] 数据库更新失败`);
        }
    });
};
let expired = accessTokenInfo =>
{
    if (accessTokenInfo.length === 0)
    {
        return true;
    }
    else
    {
        let timeRemaining = accessTokenInfo[ 0 ].expires_in - Date.now ();
        let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
        console.log (`\n[${time}][access_token]  过期还有${timeRemaining}毫秒`);
        return (accessTokenInfo.expires_in - Date.now ()) < 30000;
    }
};
let queryAccessTokenFromDatabase = () =>
{
    accessTokenDao.findAccessToekn (( done ) =>
    {
        if (done.isSuccess)
        {
            if (expired (done.result))
            {
                queryAccessTokenFromWechat ();
            }
            else
            {
                let time = (new Date).format ('yyyy-MM-dd HH:mm:ss');
                accessToken = done.result[ 0 ].access_token;
                console.log (`[${time}][access_token]  ${accessToken}`);
                let timeRemaining = done.result[ 0 ].expires_in - Date.now ();
                jsapiTicketController.initJsapiTicket (accessToken);
                
                setTimeout (function ()
                {
                    queryAccessTokenFromWechat ();
                }, timeRemaining - 30000);
            }
        }
        else
        {
            logger.warn ('从数据库获得 access_token 信息失败');
        }
    });
};
let initAccessToken = () =>
{
    queryAccessTokenFromDatabase ();
};
module.exports = {
    initAccessToken: initAccessToken,
    getAccessToken : getAccessToken,
};